package com.huilam.restactions.common.util;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.StringTokenizer;
import java.util.Vector;

public class ClassLoaderUtil {
	
	public static ClassLoader getClassLoader(File aTarget, String aPrefix, String aSuffix, ClassLoader aParentCL)
	{
		URLClassLoader cl = new URLClassLoader(new URL[]{});

		Vector<URL> vUrls = getFileURLs(aTarget, aPrefix, aSuffix);
		if(vUrls!=null && vUrls.size()>0)
		{
			cl = new URLClassLoader(vUrls.toArray(new URL[vUrls.size()]),aParentCL);
		}

		return (ClassLoader) cl;
	}
	
	public static ClassLoader getClassLoader(String aResourceNames, ClassLoader aParentCL) 
	{
		Vector<URL> vUrls = new Vector<URL>();
		URL url = null;
		File f = null;
		StringTokenizer tk = new StringTokenizer(aResourceNames, ",");
		while(tk.hasMoreTokens())
		{
			url = null;
			f = new File(tk.nextToken().trim());
			if(f.isDirectory())
			{
				vUrls.addAll(getFileURLs(f, null, null));
			}
			else if(f.isFile())
			{
				try {
					url = f.toURI().toURL();
				} catch (MalformedURLException e) {
					f = null;
				}
			}
			
			if(url!=null)
			{
				vUrls.add(url);
			}
		}
		return new URLClassLoader(vUrls.toArray(new URL[vUrls.size()]), aParentCL);
	}
	
	private static Vector<URL> getFileURLs(File aTarget, String aPrefix, String aSuffix) 
	{
		Vector<URL> vUrls = new Vector<URL>();
		
		try{
			if(aTarget!=null)
			{
				if(aTarget.isDirectory())
				{
					//Folder
					for(File f : aTarget.listFiles())
					{
						if(f.isDirectory())
						{
							getFileURLs(f, aPrefix, aSuffix);
						}
						else if (f.isFile())
						{
							if(isMatchingName(f.getName(), aPrefix, aSuffix))
								vUrls.add(f.toURI().toURL());
						}
					}
				}
				else if(aTarget.isFile())
				{
					//File
					if(isMatchingName(aTarget.getName(), aPrefix, aSuffix))
						vUrls.add(aTarget.toURI().toURL());
				}		
			}
		}catch(MalformedURLException ex)
		{
			ex.printStackTrace();
			//throw new RuntimeException(ex);
		}
		return vUrls;
	}
	
	private static boolean isMatchingName(String aName, String aPrefix, String aSufix)
	{
		if(aPrefix!=null && !aName.startsWith(aPrefix))
			return false;
		
		if(aSufix!=null && !aName.endsWith(aSufix))
			return false;
		
		return true;
		
	}
	
}
